package com.lanhao.aot.carrierintegration.youjiyouni;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import cn.hutool.core.lang.UUID;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;

/**
 * 英国皇家邮政
 * @author KunZhou
 */
public class RoyalMailAPIUtil {
	private static final Logger LOG = LoggerFactory.getLogger(RoyalMailAPIUtil.class);
//	public static final String BASE_URL = "https://open-api-pre.youjiyouni.com";
//	public static final String PUBLICK_KEY = "test_pk_bDBvoULdKCC";
//	public static final String PRIVATE_KEY = "test_sk_RHkRlQANXlemPag";
//	public static final String LINE_ID = "1063";
//	public static final String TOKEN = "4d6P4bGWjETpW+3a5KnOhL2s00mdAs1psUEJkGqCUUdf0wp463PRU08NpGKxxIgnbjpIq9V0tjjA/gH6Xc9z/3vRPwD9eIBbCwiiTU6ZnTM=";
	public static final String BASE_URL = "https://open-api.youjiyouni.com";
	public static final String PUBLICK_KEY = "live_pk_b3J11iALRqZA";
	public static final String PRIVATE_KEY = "live_sk_UVkGfvVrzp9lAhp";
	public static final String LINE_ID = "96";
	public static final String TOKEN = "02kreqkB43/so04u7XtnjWEWA4Okb+Dwvh9F0anABa27aDrOAeP7goKyqnBH2gpgCK7UbkcxBueccM8H7jZbHzYp3HYSXH79nUb1XopbNVs=";
	
	public static void main(String[] args) {
//		getAccessToken();
		createOrder();
	}
	
	public static void getAccessToken() {
		try {
			String url = BASE_URL + "/v1/oauth/access-token";
			String onceStr = UUID.fastUUID().toString(true);
			String timeStamp = String.valueOf(System.currentTimeMillis() / 1000);
			String signStr = PUBLICK_KEY + "+" + onceStr + "+" + PRIVATE_KEY + "+" + timeStamp;
			String sign = SecureUtil.md5(signStr);
			LOG.info("原始串signStr={}, 签名后sign={}", signStr, sign);
			// String sign = new String(DigestUtils.md5(PUBLICK_KEY + onceStr + PRIVATE_KEY + timeStamp), "UTF-8");
			JSONObject o = new JSONObject();
			o.put("pk", PUBLICK_KEY);
			o.put("onceStr", onceStr);
			o.put("timestamp", timeStamp);
			o.put("sign", sign);
			String respBody = HttpRequest.post(url).body(o.toJSONString()).execute().body();
			LOG.info("调用token接口request={}, 返回结果resp={}", o.toJSONString(), respBody);
			
			JSONObject respObject = JSON.parseObject(respBody);
			JSONObject metaObject = respObject.getJSONObject("meta");
			int code = metaObject.getIntValue("code");
			String msg = metaObject.getString("msg");
			if (code == 0) {
				JSONObject response = respObject.getJSONObject("response");
				int expireIn = response.getIntValue("expire_in");
				String accessToken = response.getString("access-token");
				LOG.info("调用token接口获取到的token：{}， 有效期 {} 秒", accessToken, expireIn);
			} else {
				LOG.info("调用token接口失败，原因：{}", msg);
			}
		} catch (Exception e) {
			LOG.info("调用token接口失败，原因：{}", e.getMessage());
		}
	}
	
	public static void createOrder() {
		JSONObject o = new JSONObject();
		o.put("line_id", LINE_ID);
		o.put("customer_ref", "ref123456");
//		o.put("is_charged", "0");
		
		JSONObject sender = new JSONObject();
		sender.put("country_code", "GB");
		sender.put("full_name", "Arpana Sunuwar");
		sender.put("city", "London");
		sender.put("post_code", "W139QU");
		sender.put("phone", "07428405089");
		sender.put("address1", "189 Northfields Avenue");
		sender.put("address2", "");
		o.put("sender", sender);
		
		JSONObject consignee = new JSONObject();
		consignee.put("post_code", "SE7 7RU");
		consignee.put("address1", "Unit 2265,Unit 6,Charlton Gate Business Park,Anchor and Hope Lane,");
		consignee.put("address2", "");
		consignee.put("full_name", "UK-RTN-AE");
		consignee.put("company", "");
		consignee.put("phone", "+447897159358");
		consignee.put("email", "");
		consignee.put("province", "England");
		consignee.put("city", "London");
		consignee.put("country_code", "GB");
		consignee.put("house_no", "");
		o.put("consignee", consignee);
		
		JSONArray shipments = new JSONArray();
		
		JSONObject shipment = new JSONObject();
		shipment.put("case_number", "001");
		shipment.put("length", "12");
		shipment.put("width", "23");
		shipment.put("height", "34");
		shipment.put("weight", "0.3");
		JSONArray goods = new JSONArray();
		JSONObject good = new JSONObject();
		good.put("customs_price", 12.4);
		good.put("name", "test");
		good.put("weight", 0.3);
		goods.add(good);
		shipment.put("goods", goods);
		shipments.add(shipment);
		o.put("shipments", shipments);
		
		String url = BASE_URL + "/v1/order/create";
		Map<String, String> header = new HashMap<>();
		header.put("Access-Token", TOKEN);
		String respBody = HttpRequest.post(url).addHeaders(header).body(o.toJSONString()).execute().body();
		LOG.info("调用创建订单接口request={}, 返回结果resp={}", o.toJSONString(), respBody);
		
		JSONObject respObject = JSON.parseObject(respBody);
		JSONObject metaObject = respObject.getJSONObject("meta");
		int code = metaObject.getIntValue("code");
		String msg = metaObject.getString("msg");
		if (code == 0) {
			JSONObject response = respObject.getJSONObject("response");
			String order_id = response.getString("order_id");
			String label = response.getString("label");
			JSONArray shipmentsResponse = response.getJSONArray("shipments");
			JSONObject shipmentResponse = shipmentsResponse.getJSONObject(0);
			String trackingNo = shipmentResponse.getString("track_no");
			LOG.info("调用创建订单接口成功，order_id：{}，label：{}，trackingNo：{}", order_id, label, trackingNo);
		} else {
			LOG.info("调用创建订单接口失败，原因：{}", msg);
		}
		
	}
	
}
